package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.domain.bank.Gender;
import com.acme.bankapp.domain.bank.account.Account;
import com.acme.bankapp.domain.bank.account.CheckingAccount;
import com.acme.bankapp.domain.bank.account.SavingsAccount;
import com.acme.bankapp.domain.bank.exception.BadStringToParseClient;

import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class BankDataLoaderService {
    public static Client parseString(String str) throws BadStringToParseClient {
        try {
            StringTokenizer st = new StringTokenizer(str, ";");

            Map<String, String> m = new HashMap<>();

            while (st.hasMoreTokens()) {
                StringTokenizer field = new StringTokenizer(st.nextToken(), "=");
                m.put(field.nextToken(), field.nextToken());
            }

            int balance = Integer.valueOf(m.get("balance"));
            int overdraft = Integer.valueOf(m.get("overdraft"));
            String name = m.get("name");
            Gender gender = "m".equals(m.get("gender")) ? Gender.MALE : Gender.FEMALE;
            Account acc = "c".equals(m.get("accounttype")) ? new CheckingAccount(balance, overdraft) : new SavingsAccount(balance);

            return new Client(name, gender, acc);
        } catch (Exception e) {
            //TODO log it
            System.out.println("ClientParser error, can't parse '" + str + "'");
            throw new BadStringToParseClient();
        }
    }

    public static String clientToString(Client client) {
        if (client == null)
            throw new IllegalArgumentException("client is null");
        return new StringBuilder("").append(client.getAccount().toString())
                .append("name=").append(client.getName()).append(";")
                .append("gender=").append(client.getGender() == Gender.FEMALE ? "f" : "m").append(";\n").toString();
    }
}
